//
//  LLBaseViewController.m
//  LLAccountSDK
//
//  Created by xuyf on 14-2-14.
//  Copyright (c) 2014年 LianLian. All rights reserved.
//

#import "PxBaseViewController.h"
#import "AFHTTPRequestOperation.h"

@interface PxBaseViewController ()<PxTabBarDelegate>

@end

@implementation PxBaseViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(replaceWithLogin:) name:@"login" object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    [self setTabbar];
    [self setLeftBack];
    self.view.backgroundColor = [UIColor colorWithHTMLStr:@"eeeeee"];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
//    [self setLeftBack];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIView*)setLogoTitleViewWithTitle:(NSString*)title
{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
//    titleView.backgroundColor = [UIColor colorWithHTMLStr:@"110000"];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
    titleLabel.font = [UIFont systemFontOfSize:22.f];
    titleLabel.textColor = self.navigationController.navigationBar.titleTextAttributes[NSForegroundColorAttributeName];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = title;
    titleLabel.height = TITLE_HEIGHT;
    
    [titleView addSubview:titleLabel];
    
    self.navigationItem.titleView = titleView;
    
    return titleView;
}

- (void)setLeftBack
{
    //自定义返回按钮
    UIImage *backButtonImage = [[UIImage imageNamed:@"Images/icon-back"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, -15)];//(0, 15, 0, -8)
//    UIImage *backButtonImage = [UIImage imageNamed:@"Images/icon-back"];
    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    //将返回按钮的文字position设置不在屏幕上显示
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    
    UIColor *titleFontColor = [UIColor colorWithHTMLStr:@"000000"];
    UIImage *img = [PxGlobal imageWithColor:[UIColor colorWithHTMLStr:@"ffffff"]];
    if ([LLYTSmallUtil iOSBigVersion] >= 6.5) {
        
        [self.navigationController.navigationBar setBackgroundImage:img
                                 forBarPosition:UIBarPositionTopAttached
                                     barMetrics:UIBarMetricsDefault];
        
        
        [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : titleFontColor,
                                                      NSFontAttributeName : [UIFont systemFontOfSize:20],
                                                      }];
        
    }
    else
    {
        [self.navigationController.navigationBar setBackgroundImage:img
                                  forBarMetrics:UIBarMetricsDefault];
        
        [self.navigationController.navigationBar setTitleTextAttributes:@{UITextAttributeTextColor : titleFontColor,
                                                      UITextAttributeFont : [UIFont systemFontOfSize:20],
                                                      UITextAttributeTextShadowColor: [UIColor clearColor],
                                                      UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetZero],
                                                      }];
        
        
    }
}

+ (instancetype)viewControllerWithIncomingParam:(id)param
{
    PxBaseViewController *vc = [[self alloc] initWithNibName:nil bundle:nil];
    
    if ([vc isKindOfClass:[PxBaseViewController class]]) 
    {
        vc.incomingParam = param;
    }
    
    return vc;
}

- (void)pushViewController:(NSString*)vcClassName withIncomingParam:(id)param
{
    id vc = [NSClassFromString(vcClassName) viewControllerWithIncomingParam:param];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushNeedLoginViewController:(NSString*)vcClassName withIncomingParam:(id)param
{
    if ([PxNetSession sharedSession].currentUser == nil) {
        [self gotoLogin];
        return;
    }
    
    [self pushViewController:vcClassName withIncomingParam:param];
}

- (void)gotoLogin
{
//    NSString *lastLogin = [LLSSKeychain passwordForService:@"lastLogin"
//                                                   account:@"lastLogin"];
//    
//    NSString *lockPass = [LLSSKeychain passwordForService:@"lockpass"
//                                                  account:lastLogin];
//    
//    NSString *autoLoginPass = [LLSSKeychain passwordForService:@"login"
//                                                  account:lastLogin];
////    if (lockPass != nil && autoLoginPass != nil)
////    {
////        [self pushViewController:@"PxUnLockViewController" withIncomingParam:nil];
////        return;
    ////    }
    [self pushViewController:@"PxHomeViewController" withIncomingParam:nil];
//    [self pushViewController:@"PxMapViewController" withIncomingParam:nil];
}

- (void)replaceWithLogin:(NSNotification*)notify
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self pushRootViewController:@"PxLoginViewController" withIncomingParam:nil];
//    NSString *str = [notify object];
//    NSDictionary *data = [str JSONObject];
//    [self pushViewController:@"PxOauthWebViewController" withIncomingParam:@{@"name":@"登录",
//                                                                        @"url":data[RESULT_DESC],
//                                                                        @"isNeedScale":@"1"
//                                                                        }];
}

- (void)replaceViewController:(NSString*)vcClassName withIncomingParam:(id)param
{
//    NSLog(@"count: %d", self.navigationController.viewControllers.count);
    NSMutableArray *vcStack = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    
    [vcStack removeLastObject];
    
    id vc = [NSClassFromString(vcClassName) viewControllerWithIncomingParam:param];
    
    [vcStack addObject:vc];
    
    [self.navigationController setViewControllers:vcStack animated:YES];
}

- (void)pushRootViewController:(NSString*)vcClassName withIncomingParam:(id)param
{
    //    NSLog(@"count: %d", self.navigationController.viewControllers.count);
    NSMutableArray *vcStack = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    
    [vcStack removeAllObjects];
    
    id vc = [NSClassFromString(vcClassName) viewControllerWithIncomingParam:param];
    
    [vcStack addObject:vc];
    
    [self.navigationController setViewControllers:vcStack animated:YES];
}

- (void)replaceViewController:(id)param
{
    NSMutableArray *vcStack = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    
    [vcStack removeLastObject];
    
    [vcStack addObject:param];
    
    [self.navigationController setViewControllers:vcStack animated:YES];
}

- (void)popToViewController:(NSString *)vcClassName
{
    for (UIViewController *viewContrl in [self.navigationController viewControllers]) {
        if ([viewContrl isKindOfClass:NSClassFromString(vcClassName)]) {
            [self.navigationController popToViewController:viewContrl animated:YES];
            continue;
        }
    }
}

- (void)popToLastControllerWithIncomingParam:(id)param
{
    NSMutableArray *vcStack = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    PxBaseViewController *viewContrl = vcStack[vcStack.count-2];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:viewContrl.incomingParam];
    [dic addEntriesFromDictionary:param];
    viewContrl.incomingParam = param;
    [self.navigationController popToViewController:viewContrl animated:YES];
}

- (void)popToViewController:(NSString *)vcClassName withIncomingParam:(id)param
{
    for (PxBaseViewController *viewContrl in [self.navigationController viewControllers]) {
        if ([viewContrl isKindOfClass:NSClassFromString(vcClassName)]) {
            viewContrl.incomingParam = param;
            [self.navigationController popToViewController:viewContrl animated:YES];
            continue;
        }
    }
}

- (void)back
{
    NSArray *vcStack = self.navigationController.viewControllers;
    if ([vcStack count] > 1) 
    {
        id lastVc = [vcStack lastObject];  // 应该这个就是self，需要判断么？
        id willShowVc = [vcStack objectAtIndex:vcStack.count - 2];
        
        if ([lastVc isKindOfClass:[PxBaseViewController class]]
            && [willShowVc isKindOfClass:[PxBaseViewController class]]) 
        {
            [willShowVc topViewControllerExit:((PxBaseViewController*)lastVc).exitParam];
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)topViewControllerExit:(id)controllerExitParam
{
    
}

- (void)setTabbar
{
    
    NSMutableArray *items = [NSMutableArray array];
    
    for (NSString *imageName in @[@"首页.png", @"首页-高亮.png",
                                  //                                  @"提油信息.png", @"提油信息-高亮.png",
                                  @"订单.png", @"订单-高亮.png",
                                  @"下单.png", @"下单-高亮.png",
                                  @"我的.png", @"我的-高亮.png",])
    {
        [items addObject:[NSString stringWithFormat:@"Images/%@", imageName]];
    }
    
    CGFloat top = self.view.height - TABBAR_HEIGHT - TITLE_HEIGHT;
    
    if ([LLYTSmallUtil iOSBigVersion] >= 6.5) {
        top -= STATUSBAR_HEIGHT;
    }
    
    PxTabBar *tabbarView = [[PxTabBar alloc] initWithFrame:CGRectMake(0, top, self.view.width, TABBAR_HEIGHT)];
    self.tabBar = tabbarView;
    tabbarView.backgroundColor = [UIColor colorWithHTMLStr:@"9A32CD"];
    [tabbarView setImageNameList:items];
    [tabbarView setBtnTitle:@[@"首页", @"订单", @"下单", @"我的"]];
    [self.view addSubview:tabbarView];
    tabbarView.tabDelegate = self;
    
    UIView *lineview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 1)];
    [self.view addSubview:lineview];
    lineview.top = tabbarView.top-1;
    lineview.backgroundColor = [UIColor colorWithHTMLStr:@"c0c0c0"];
}

- (void)tabSelected:(PxTabBar*)tabbar index:(NSInteger)index
{
    if (tabbar.currentIndex == index)
        return;
    
    if (index == 3 || index == 2) {
        if ([PxNetSession sharedSession].currentUser == nil) {
            [self gotoLogin];
            return;
        }
    }
    
    switch (index) {
        case 0:
            [self pushRootViewController:@"PxHomeViewController" withIncomingParam:nil];
            break;
        case 1:
            [self pushRootViewController:@"PxLoginViewController" withIncomingParam:nil];
//            [self replaceViewController:@"PxPlaceDownViewController" withIncomingParam:nil];
//            [self replaceViewController:@"PxMapViewController" withIncomingParam:nil];
            break;
        case 2:
            [self pushRootViewController:@"PxPlaceOrderViewController" withIncomingParam:nil];
            break;
        case 3:
            [self pushRootViewController:@"PxUserHomeViewController" withIncomingParam:nil];
            break;
            
        default:
            break;
    }
    
}

-(void)removeAllSubViews
{
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
}

- (BOOL)isEmpty:(NSArray *)fields
{
    NSArray *textFields = fields;
    for (UIView *view in textFields) {
        if (![view isKindOfClass:[LLYTTextField class]])
            continue;
        LLYTTextField *textField = (LLYTTextField *)view;
        if (nil == textField.text || 0 == textField.text.length) {
            UIView *label = textField.leftView;
            NSString *msg = @"表单有空字段，请检查内容";
            if ([label isKindOfClass:[UILabel class]]) {
                msg = [NSString stringWithFormat:@"%@ 不能为空", ((UILabel*)label).text];
            }
        
            [self showMSG:msg withType:0];
            
            return YES;
        }
    }
    return NO;
}

- (void)showMSG:(NSString *)msg withType:(int)type
{
    NSString *title = @"提示";
    switch (type) {
        case 0:
            title = @"提示";
            break;
        case 1:
            title = @"错误";
            break;
        default:
            break;
    }
    [LLAlertService sysAlertWithTip:msg withTitle:title];
}

@end
